package org.gongliang.jsmile.common.aop;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.gongliang.jsmile.common.base.JSmileResult;
import org.gongliang.jsmile.common.enums.KException;
import org.gongliang.jsmile.common.exception.JSmileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author 龚亮
 * @date 2016年11月12日 下午3:19:56
 */
// @ControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(KExceptionHandler.class);

	/**
	 * 拦截业务异常
	 */
	@ExceptionHandler(JSmileException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public JSmileResult notFount(JSmileException e) {
		logger.error("业务异常:", ExceptionUtils.getStackTrace(e));
		return new JSmileResult(e.getErrCode(), e.getErrMsg(), JSmileResult.STATE_ERROR);
	}

	/**
	 * 用户未登录
	 */
	@ExceptionHandler(AuthenticationException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public String unAuth(AuthenticationException e) {
		logger.error("用户未登陆：", ExceptionUtils.getStackTrace(e));
		return "login";
	}

	/**
	 * 账号被冻结
	 */
	@ExceptionHandler(DisabledAccountException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public String accountLocked(DisabledAccountException e, Model model) {
		logger.error("账号被冻结：", ExceptionUtils.getStackTrace(e));
		return "login";
	}

	/**
	 * 账号或密码错误
	 */
	@ExceptionHandler(CredentialsException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public String credentials(CredentialsException e) {
		logger.error("账号或密码错误：", ExceptionUtils.getStackTrace(e));
		return "login";
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public JSmileResult sysError(Exception e) {
		logger.error("运行时异常:", ExceptionUtils.getStackTrace(e));
		return JSmileResult.error(KException.REQUEST_ERROR);
	}

}
